package com.fjp.heartguard.ui.question.fragment

import android.content.Intent
import android.content.pm.PackageManager
import android.graphics.Color
import android.os.Bundle
import android.os.Handler
import android.os.Looper
import android.provider.Settings
import android.view.View
import androidx.core.app.ActivityCompat
import androidx.core.content.ContextCompat
import com.fjp.heartguard.R
import com.fjp.heartguard.app.base.BaseFragment
import com.fjp.heartguard.app.ext.showToast
import com.fjp.heartguard.app.util.AppUtils
import com.fjp.heartguard.databinding.FragmentRespondentUserinfoBinding
import com.fjp.heartguard.ui.question.QuestionActivity
import com.fjp.heartguard.viewmodel.RespondentsUserInfoViewModel
import com.github.gzuliyujiang.wheelpicker.AddressPicker
import com.github.gzuliyujiang.wheelpicker.DatePicker
import com.github.gzuliyujiang.wheelpicker.annotation.AddressMode
import com.github.gzuliyujiang.wheelpicker.annotation.DateMode
import com.github.gzuliyujiang.wheelpicker.contract.OnDatePickedListener
import com.github.gzuliyujiang.wheelpicker.entity.DateEntity
import com.github.gzuliyujiang.wheelpicker.impl.UnitDateFormatter
import com.lxj.xpopup.XPopup
import com.tencent.map.geolocation.TencentLocation
import com.tencent.map.geolocation.TencentLocationListener
import com.tencent.map.geolocation.TencentLocationManager
import com.tencent.map.geolocation.TencentLocationRequest
import me.hgj.jetpackmvvm.base.appContext
import java.time.LocalDate


class RespondentUserinfoFragment : BaseFragment<RespondentsUserInfoViewModel, FragmentRespondentUserinfoBinding>(), OnDatePickedListener {
    private val REQUEST_LOCATION_PERMISSION = 1

    companion object {
        fun newInstance() = RespondentUserinfoFragment()
    }

    override fun initView(savedInstanceState: Bundle?) {
        mDatabind.viewModel = mViewModel
        mDatabind.click = ClickProxy()
        mViewModel.title.set(getString(R.string.question_title))
        mDatabind.questionTitle.setValue("受访者基本信息", resources.getColor(R.color.color_question_bottom_01), R.drawable.question_icon_01)
        if (QuestionActivity.olderInfo.name.isNotEmpty()) {
            mViewModel.name.value = QuestionActivity.olderInfo.name
            mViewModel.birthday.value = QuestionActivity.olderInfo.birthday
            mViewModel.mobile.value = QuestionActivity.olderInfo.mobile
            mViewModel.province.value = QuestionActivity.olderInfo.province
            mViewModel.city.value = QuestionActivity.olderInfo.city
            mViewModel.district.value = QuestionActivity.olderInfo.district
            mViewModel.address.value = QuestionActivity.olderInfo.address
        }

        if (mViewModel.province.value!!.length != 0) {
            mDatabind.provinceEt.setText("${QuestionActivity.olderInfo.province}-${QuestionActivity.olderInfo.city}-${QuestionActivity.olderInfo.district}")
        }
        if (QuestionActivity.olderInfo.live_type == "家") {
            mDatabind.homeRb.isChecked = true
        } else if (QuestionActivity.olderInfo.live_type == "医院") {
            mDatabind.hospitalRb.isChecked = true
        } else {
            mDatabind.nursingHomeRb.isChecked = true
        }
        mViewModel.nursingHome.value = QuestionActivity.olderInfo.institution_name
        mDatabind.liveRg.setOnCheckedChangeListener { radioGroup, i ->
            when (i) {
                R.id.homeRb -> {
                    mDatabind.nursingHomeEt.visibility = View.GONE
                    QuestionActivity.olderInfo.live_type = "家"
                }

                R.id.hospitalRb -> {
                    mDatabind.nursingHomeEt.visibility = View.GONE
                    QuestionActivity.olderInfo.live_type = "医院"
                }

                else -> {
                    QuestionActivity.olderInfo.live_type = "养老机构"
                    mDatabind.nursingHomeEt.visibility = View.VISIBLE
                    Handler().postDelayed({ mDatabind.scrollView.fullScroll(View.FOCUS_DOWN) }, 100)

                }
            }
        }
        mDatabind.sexRg.setOnCheckedChangeListener { radioGroup, i ->
            QuestionActivity.olderInfo.sex = if (i == R.id.manRb) "男" else "女"
        }
    }

    override fun createObserver() {
        super.createObserver()
        mViewModel.name.observe(this) {
            QuestionActivity.olderInfo.name = it
        }
        mViewModel.birthday.observe(this) {
            QuestionActivity.olderInfo.birthday = it
        }
        mViewModel.mobile.observe(this) {
            QuestionActivity.olderInfo.mobile = it
        }
        mViewModel.province.observe(this) {
            QuestionActivity.olderInfo.province = it
        }
        mViewModel.city.observe(this) {
            println("=========城市${it}")
            println("=========${QuestionActivity.olderInfo}")
            QuestionActivity.olderInfo.city = it
        }
        mViewModel.district.observe(this) {
            QuestionActivity.olderInfo.district = it
        }
        mViewModel.address.observe(this) {
            QuestionActivity.olderInfo.address = it
        }
        mViewModel.nursingHome.observe(this) {
            QuestionActivity.olderInfo.institution_name = it
        }
    }

    private fun showNoLocationPop() {
        XPopup.Builder(requireActivity()).asConfirm("提示", "当前手机没有开启定位服务，是否去开启", "否", "是", {
            val intent: Intent = Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS)
            startActivity(intent)
        }, {}, false).show()
    }

    inner class ClickProxy {
        fun clickBorn() {
            showBornDialog()
        }

        fun clickAddress() {
            showAddressDialog()
        }

        fun clickNext() {
            startActivity(Intent(context, QuestionActivity::class.java))
        }

        fun clickLocation() {
            if (ContextCompat.checkSelfPermission(activity!!, android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
                ActivityCompat.requestPermissions(activity!!, arrayOf<String>(android.Manifest.permission.ACCESS_FINE_LOCATION), REQUEST_LOCATION_PERMISSION)
            } else {
                location()
            }
        }
    }

    fun showBornDialog() {
        val currentDate = LocalDate.now()
        val picker = DatePicker(requireActivity())
        picker.setBackgroundResource(R.drawable.bg_white_top_round_8)
        picker.setTitle("出生日期")
        val wheelLayout = picker.wheelLayout
        wheelLayout.setDateMode(DateMode.YEAR_MONTH_DAY)
        wheelLayout.setDateLabel("", "", "")
        wheelLayout.setDateFormatter(UnitDateFormatter())
        wheelLayout.setRange(DateEntity.target(1905, 1, 1), DateEntity.target(currentDate.year, currentDate.monthValue, currentDate.dayOfMonth), DateEntity.today())
        wheelLayout.setCurtainEnabled(false)
        wheelLayout.setIndicatorEnabled(false)
        wheelLayout.setDefaultValue(DateEntity.target(1970, 1, 1))
        picker.wheelLayout.setResetWhenLinkage(false)
        picker.setOnDatePickedListener(this)
        picker.show()
    }

    fun showAddressDialog() {
        val picker = AddressPicker(requireActivity())
        picker.setBackgroundResource(R.drawable.bg_white_top_round_8)
        picker.setTitle("请选择")
        picker.okView.setTextColor(requireContext().getColor(R.color.colorAccent))
        picker.cancelView.setTextColor(requireContext().getColor(R.color.colorAccent))
        picker.titleView.setTextColor(Color.BLACK)
        picker.setAddressMode(AddressMode.PROVINCE_CITY_COUNTY)
        picker.setOnAddressPickedListener { province, city, county ->
            mViewModel.province.postValue(province.name)
            mViewModel.city.postValue(city.name)
            mViewModel.district.postValue(county.name)
            mDatabind.provinceEt.setText("${province.name}-${city.name}-${county.name}")
        }
        picker.show()
    }

    fun location() {
        if (!AppUtils.checkGPSIsOpen(requireContext())) {
            showNoLocationPop()

            return
        }
        showLoading("正在获取地理位置")
        TencentLocationManager.setUserAgreePrivacy(true)
        val mLocationManager = TencentLocationManager.getInstance(context)
        val request = TencentLocationRequest.create()
        request.isGpsFirst = true
        mLocationManager.requestSingleFreshLocation(request, object : TencentLocationListener {
            override fun onLocationChanged(location: TencentLocation?, error: Int, p2: String?) {
                dismissLoading()
                if (error == TencentLocation.ERROR_OK && location != null  && location.city != null) {
                    println("当前定位信息："+location)
                    if (location.province != null) {
                        mViewModel.province.postValue(location.province)
                    }
                    if (location.city != null) {
                        mViewModel.city.postValue(location.city)
                    }

                    if (location.district != null) {
                        mViewModel.district.postValue(location.district)
                    }

                    mViewModel.address.postValue("${location.address + location.name}")
                    mDatabind.provinceEt.setText("${location.province}-${location.city}-${location.district}")
                } else {
                    appContext.showToast("获取定位数据失败")
                }
            }

            override fun onStatusUpdate(p0: String?, p1: Int, p2: String?) {

            }

        }, Looper.getMainLooper())
    }

    override fun onDatePicked(year: Int, month: Int, day: Int) {
        mViewModel.birthday.postValue("${year}-${String.format("%02d", month)}-${String.format("%02d", day)}")
    }

}
